package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/users")
public class UsersController {
    
    @Autowired
    private UserInfoService userInfoService;
    
    @Autowired
    private UserService userService;

    /**
     * 查询用户资料
     */
    @GetMapping
    public ResponseEntity users(Long userID,@RequestHeader("Authorization") String token){
        //判断token是否合法
        //获取用户ID
        //判断用户ID
        if (userID == null){
            userID = UserHolder.getUserId();
        }
        UserInfoVo userInfoVo = userInfoService.findById(userID);
        return ResponseEntity.ok(userInfoVo);
    }

    /**
     * 更新用户资料
     */
    @PutMapping
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        //判断token是否合法
        //获取用户ID
        //设置用户ID
        userInfo.setId(UserHolder.getUserId());
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 修改手机号,发送短信验证码
     */
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity sendVerificationCode(){
        //获取手机号
        String phone = UserHolder.getMobile();
        //发送验证码
        userService.getCode(phone);
        return ResponseEntity.ok(null);
    }

    /**
     * 修改手机号,校验验证码
     */
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity checkVerificationCod(@RequestBody Map map){
        //获取验证码
        String code = (String) map.get("verificationCode");
        Map vf = userService.verification(code);

        return ResponseEntity.ok(vf);
    }

    /**
     * 修改手机号,保存
     */
    @PostMapping("/phone")
    public ResponseEntity save(@RequestBody Map map){
        //获取手机号
        String phone = (String) map.get("phone");

        userService.amend (phone);
        return ResponseEntity.ok(null);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 计数
     */
    @GetMapping("/counts")
    public ResponseEntity counts(){
        Map<String,Integer> map = userInfoService.counts();
        return ResponseEntity.ok(map);
    }
}
